package model;

import cn.edu.scau.biubiusuisui.annotation.FXEntity;
import cn.edu.scau.biubiusuisui.annotation.FXField;
import com.sun.tools.classfile.ConstantPool;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;

@FXEntity
public class Downloader {

    private int total;

    private int now;

    @FXField
    private String url;

    @FXField
    private String savePath;
    @FXField
    private Double download_rate = new Double(0.0);

    public void download(Paper paper) {
        Thread thread= new Thread(() -> {
            saveUrlAs(url, savePath, paper.toString(), "GET");
        });
        thread.setDaemon(true);
        thread.start();
    }

    public File saveUrlAs(String url, String filePath, String filename, String method) {
        //System.out.println("fileName---->"+filePath);
        //创建不同的文件夹目录
        File file = new File(filePath);
        //判断文件夹是否存在
        if (!file.exists()) {
            //如果文件夹不存在，则创建新的的文件夹
            file.mkdirs();
        }
        FileOutputStream fileOut = null;
        HttpURLConnection conn = null;
        InputStream inputStream = null;
        try {
            // 建立链接
            URL httpUrl = new URL(url);
            conn = (HttpURLConnection) httpUrl.openConnection();
            //以Post方式提交表单，默认get方式
            conn.setRequestMethod(method);
            conn.setDoInput(true);
            conn.setDoOutput(true);
            // post方式不能使用缓存
            conn.setUseCaches(false);
            //连接指定的资源
            conn.connect();

            double total = Double.valueOf(conn.getHeaderField("Content-Length"));
            //System.out.println(length);
            //获取网络输入流
            inputStream = conn.getInputStream();
            BufferedInputStream bis = new BufferedInputStream(inputStream);
            //判断文件的保存路径后面是否以/结尾
            if (!filePath.endsWith("/")) {
                filePath += "/";
            }
            //写入到文件（注意文件保存路径的后面一定要加上文件的名称）
            fileOut = new FileOutputStream(filePath + filename);
            BufferedOutputStream bos = new BufferedOutputStream(fileOut);

            byte[] buf = new byte[4096];
            int length = bis.read(buf);
            int read_length = length;
            //保存文件
            while (length != -1) {
                setDownload_rate((double) read_length / total);
                bos.write(buf, 0, length);
                length = bis.read(buf);
                read_length += length;
            }
            bos.close();
            bis.close();
            conn.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("抛出异常！！");
        }
        return file;
    }

    public int getTotal() {
        return total;
    }

    public void setTotal(int total) {
        this.total = total;
    }

    public int getNow() {
        return now;
    }

    public void setNow(int now) {
        this.now = now;
    }

    public double getDownload_rate() {
        return download_rate;
    }

    public void setDownload_rate(double download_rate) {
        this.download_rate = download_rate;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getSavePath() {
        return savePath;
    }

    public void setSavePath(String savePath) {
        this.savePath = savePath;
    }

    public void setDownload_rate(Double download_rate) {
        this.download_rate = download_rate;
    }
}
